package com.example.demo.controller;

import com.example.demo.entity.Comment;
import com.example.demo.param.CommentParam;
import com.example.demo.service.CommentService;
import com.example.demo.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@CrossOrigin
@RestController
@Slf4j
@RequestMapping("/comment")
public class CommentController {

    @Resource
    private CommentService commentService;

    @Resource
    private RedisTemplate<String, Integer> redisTemplate;

    @GetMapping("/myComment")
    public Result myComment(Long userId,Integer pageNo,String token){
        if (!StringUtils.hasText(token)){
            Result.error("用户未登录");
        }
        List<Comment> list = commentService.findCommentByUserId(userId,pageNo);
        return Result.ok().data("list",list);
    }

    @GetMapping("/poetryComment")
    public Result poetryComment(Long poetryId,Integer pageNo){
        List<Comment> list = commentService.findPoetryComment(poetryId,pageNo);
        return Result.ok().data("list",list);
    }

    @PostMapping("/insertComment")
    public Result insertComment(@RequestBody CommentParam commentParam){
        /*发表 诗词评论 type入参为 1
        * 发表 动态评论 type入参为 2*/
        Integer flag = commentService.insertComment(commentParam);
        if (flag>0){
            return Result.ok();
        }else {
            return Result.error("插入失败");
        }
    }

    /*点赞
     * type = 1 表示对评论点赞
     * type = 2 表示对动态本身点赞
     * */
    @GetMapping("/addLike")
    public Result addLike(Long id,Integer type){
        String key = type+"_"+id;
        redisTemplate.opsForValue().increment(key);
        return Result.ok();
    }

    /*取消点赞*/
    @GetMapping("/deleteLike")
    public Result deleteLike(Long id,Integer type){
        String key = type+"_"+id;
        redisTemplate.opsForValue().increment(key,-1);
        return Result.ok();
    }


}
